/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package filter;

import java.io.IOException;
import javax.persistence.EntityManager;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import util.JPAUtil;

/**
 *
 * @author Ronei
 */
public class TransacaoFilter implements Filter{

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
       
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
      
        EntityManager em =  JPAUtil.getEntityManager();
        try {
            em.getTransaction().begin();
            
            request.setAttribute("entityManager", em);
            chain.doFilter(request, response);
            em.getTransaction().commit();
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServletException(e);
            
        } finally {
            em.close();
        }
    }

    @Override
    public void destroy() {
        
    }
    
}
